﻿module.exports = function (port) {
    const koa = require('koa');
    const koaBodyparser = require('koa-bodyparser');
    // 注意require('koa-router')返回的是函数:
    const koaRouter = require('koa-router')();

    const app = new koa();
    app.use(koaBodyparser());

    // log request URL:
    app.use(async (ctx, next) => {
        console.log(`Process ${ctx.request.method} ${ctx.request.url}...`);
        await next();
    });
    koaRouter.get('/home/:name', async (ctx, next) => {

        var name = ctx.params.name;
        ctx.response.body = `<h1>Hello ${name}</h1>`;

    });
    koaRouter.get('/', async (ctx, next) => {
        ctx.response.body = '<h1>Index</h1>';
    });

    koaRouter.post('/sign', async (ctx, next) => {
        var name = ctx.request.body.name || '',
            password = ctx.request.body.password || '';

        console.log(`signin with name: ${name}, password: ${password}`);

        if (name === 'koa' && password === '12345') {
            ctx.response.body = `<h1>Welcome, ${name}!</h1>`;
        } else {
            ctx.response.body = `<h1>Login failed!</h1><p><a href="/">Try again</a></p>`;
        }
    });

    app.use(koaRouter.routes());

    app.listen(port);
    console.log('app started at port ' + port);
}